# -*- coding:utf-8 -*-
# @Time: 2020/8/4 15:48
# @Author: liupengfei
# @File: serializersfield.py
import datetime
from django.utils import timezone
from rest_framework import serializers


def getAttributeValue(instance, obj):
    if '.' in instance.source:
        k = instance.source.split('.')
        for i in range(len(k)):
            if hasattr(obj, k[i]):
                obj = getattr(obj, k[i])
        val = obj
    else:
        val = getattr(obj, instance.source)
    return val


class DelayTimeCharField(serializers.CharField):
    def get_attribute(self, instance):
        return instance

    def to_representation(self, obj):
        val = getAttributeValue(self, obj)
        delay = timezone.now() - val

        if delay:
            if delay.days and delay.days < 0:
                delay = u'刚刚'
            elif delay.days and delay.days > 0:
                delay = u'{}天前'.format(delay.days)
            elif delay.seconds > 60:
                delay = delay.seconds / 60
                if delay < 60:
                    delay = u'{}分钟前'.format(int(delay))
                elif delay < 60 * 24:
                    delay = u'{}小时前'.format(int(delay / 60))
            else:
                delay = u'刚刚'
        else:
            delay = u''
        return delay


class RemainTimeCharField(serializers.CharField):
    def get_attribute(self, obj):
        return obj

    def to_representation(self, obj):
        val = getAttributeValue(self, obj)
        end_time = val + datetime.timedelta(days=3)
        if end_time < timezone.now() or end_time == timezone.now():
            return u''
        remain = end_time - timezone.now()

        if remain:
            if remain.days:
                remain = u'还有{}天'.format(remain.days)
            elif remain.seconds:
                remain = remain.seconds / 60
                if remain < 60:
                    remain = u'还有{}分钟'.format(int(remain))
                elif remain < 60 * 24:
                    remain = u'还有{}小时'.format(int(remain / 60))
            else:
                remain = u''
        else:
            remain = u''
        return remain
